package com.happy.xiao.consumer.callback.rabbitmq;

import com.fasterxml.jackson.core.type.TypeReference;
import com.happy.xiao.common.rabbitmq.bean.MessageReliabilityDelay;
import com.happy.xiao.common.rabbitmq.db.entity.MessageLog;
import com.happy.xiao.common.rabbitmq.db.service.IMessageLogService;
import com.happy.xiao.common.rabbitmq.BaseConsumerListener;
import com.happy.xiao.common.rabbitmq.util.MessageUtil;
import com.happy.xiao.common.utils.StringUtil;
import com.happy.xiao.common.utils.Util;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 可靠性【延时队列监听】
 */
@Component("ReliabilityDelayListener")
public class ReliabilityDelayListener extends BaseConsumerListener implements ChannelAwareMessageListener {

    @Autowired
    IMessageLogService iMessageLogService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String redisPrefix = "rabbitmq-reliability-delay-";
        try {

            System.out.println("可靠性 死信队列 =====  " + StringUtil.time());

            String messageContent = MessageUtil.getMessageContent(message);
            MessageReliabilityDelay bean = Util.JsonToObject(new TypeReference<MessageReliabilityDelay>() {
            }, messageContent);

            // 通过消息id,获取到正常消息的数据，如果消费成功之后。则不做处理。如果消费成功。则进行补偿机制
            String messageId = bean.getMessageId();
            String handleUrl = bean.getHandleUrl(); // 这个值是用来进行补偿机制的

            MessageLog byMessageId = iMessageLogService.findByMessageId(messageId);

            if (byMessageId != null) {
                System.out.println(byMessageId.toString());
            }

            // 相应
            handleSuccessMessage(channel, message, redisPrefix);
        } catch (Exception e) {
            e.printStackTrace();

            // TODO: 这里要用缓存控制一下，重入队列
            // 先判断redis中，是否存在着个异常消息次数，如果不存在，则添加到redis
            // 判断redis中的次数，如果超过一定的次数，如10次，则把这个消息丢弃
            handleErrorMessage(channel, message, redisPrefix);
        }
    }
}
